﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace JHoelsch.DataClases.Serialization
{
    public class BinarySerializationTool
    {
        static public void writeToFile<T>(T toSave, string filename)
        {
            if (toSave == null)
                return;
            IFormatter formatter = new BinaryFormatter();
            Stream stream = new FileStream(filename,
                                     FileMode.Create,
                                     FileAccess.Write, FileShare.None);
            formatter.Serialize(stream, toSave);
            stream.Close();
        }
        public static T readFromFile<T>(string filename) where T : class
        {
            try
            {
                IFormatter formatter = new BinaryFormatter();
                Stream stream = new FileStream(filename,
                                          FileMode.Open,
                                          FileAccess.Read,
                                          FileShare.Read);
                T obj = (T)formatter.Deserialize(stream);
                stream.Close();
                if (obj != null)
                    return obj;
            }
            catch (Exception exc)
            {
                System.Diagnostics.Debug.WriteLine(exc.StackTrace);
            }
            return default(T);
        }
    }
}
